import { currentUserInfo } from '@/api/user'
import { signIn, smsSignIn, mailSignIn, signOut } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {
      userId: -1,
      loginName: '无',
      userName: '我的昵称',
      avatar: '',
      hasVoice: true,
      webBeginner: false,
      hasPassword: true
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = JSON.parse(JSON.stringify(userInfo))
  }
}

const actions = {
  // 登录
  async login (_, { userInfo: { username, credential }, type = 'password' }) {
    try {
      let response
      switch (type) {
        case 'password':
          response = await signIn(username.trim(), credential)
          break
        case 'verification':
          response = await smsSignIn(username.trim(), credential)
          break
        case 'email':
          response = await mailSignIn(username.trim(), credential)
          break
        default:
          return Promise.reject(new Error('错误的登录类型'))
      }
      const { data: { token, refreshToken } } = response
      setToken('token', token)
      setToken('refreshToken', refreshToken)
      return response
    } catch (err) {
      return Promise.reject(err)
    }
  },

  // 获取用户信息
  async getUserInfo ({ commit }) {
    try {
      const response = await currentUserInfo()
      const { data } = response
      commit('SET_USERINFO', data)
      return response
    } catch (err) {
      return Promise.reject(err)
    }
  },

  // 用户登出
  async logout ({ commit }) {
    try {
      await signOut()
      removeToken()
      commit('RESET_STATE')
    } catch (err) {
      return Promise.reject(err)
    }
  },

  // 重置token
  async resetToken ({ commit }) {
    removeToken()
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
